// 解析查询字符串
function parseQueryString(str) {
    var obj = {}
    var r1 = str.split('&')
    for (var i = 0; i < r1.length; i++) {
      var tmp = r1[i].split('=')
      obj[tmp[0]] = tmp[1]
    }
    return obj
  }
   
  // 转换查询字符串
  /* function queryStringify(obj) {
    var str = ''
    for (var k in obj) {
      str += k + '=' + obj[k] + '&'
    }
    return str.slice(0, -1)
  } */

  // 封装时间差函数
  function diffTime(time1, time2) {
    var t1 = time1.getTime()
    var t2 = time2.getTime()
    var sub = Math.ceil(Math.abs(t2 - t1) / 1000)
   
    return {
      day: parseInt(sub / (60 * 60 * 24)),
      hours: parseInt(sub % (60 * 60 * 24) / (60 * 60)),
      minutes: parseInt(sub % (60 * 60) / 60),
      seconds: sub % 60
    }
  }

  // 范围内的随机数字
function randomNum(a, b) {
    return Math.floor(Math.random() * (Math.abs(a - b) + 1)) + Math.min(a, b)
  }
   
  // 随机颜色字符串
  function randomColor() {
    var res = '#'
    for (var i = 1; i <= 3; i++) {
      var n = randomNum(0, 255)
      var r1 = n.toString(16)
      if (n <= 15) r1 = '0' + r1
      res += r1
    }
    return res
  }
  

  
  // 运动函数
  function move(ele, options, fn = function () {}) {
    let count = 0
    for (let key in options) {
      count++
      if (key === 'opacity') options[key] *= 100
      const timer = setInterval(() => {
        let current
        if (key === 'opacity') {
          current = window.getComputedStyle(ele)[key] * 100
        } else {
          current = parseInt(window.getComputedStyle(ele)[key])
        }
        let distance = (options[key] - current) / 10
        distance = distance > 0 ? Math.ceil(distance) : Math.floor(distance)
        if (current === options[key]) {
          clearInterval(timer)
          count--
          if (count === 0) fn()
        } else {
          if (key === 'opacity') {
            ele.style[key] = (current + distance) / 100
          } else {
            ele.style[key] = current + distance + 'px'
          }
        }
      }, 20)
    }
  }

  // 选项卡
  function Tabs(select, type = 'click') {
    this.ele = document.querySelector(select)
    this.btns = this.ele.querySelectorAll('ul > li')
    this.boxs = this.ele.querySelectorAll('ol > li')
    this.type = type
    this.init()
  }
  Tabs.prototype.init = function () {
    for (let i = 0; i < this.btns.length; i++) {
      this.btns[i].addEventListener(this.type, () => {
        for (let j = 0; j < this.btns.length; j++) {
          this.btns[j].className = ''
          this.boxs[j].className = ''
        }
        this.btns[i].classList.add('active')
        this.boxs[i].classList.add('active')
      })
    }
  }


  // 对象转换成查询字符串方法
function queryStringify(obj) {
  let str = ''
 
  for (let k in obj) {
    str += k + '=' + obj[k] + '&'
  }
 
  return str.slice(0, -1)
}
 
// 封装 ajax 的代码
function ajax(options = {}) {
  const { url, method, async, data, headers, dataType, success } = options
  if (!url) throw new Error('url 为必填选项, 请传递此项内容, ^_^')
  if (!(method === undefined || /^(get|post)$/i.test(method))) throw new Error('method 目前只接受 "GET" 或者 "POST" 方式, 请期待更新 (#^.^#)')
  if (!(async === undefined || typeof async === 'boolean')) throw new Error('async 需要传递一个 "Boolean" 类型数据呦 O(∩_∩)O哈哈~')
  if (!(data === undefined || typeof data === 'string' || Object.prototype.toString.call(data) === '[object Object]'))  throw new Error('data 需要传递一个 "String" 或者 "Object" 类型数据 o(*￣︶￣*)o')
  if (!(headers === undefined || Object.prototype.toString.call(headers) === '[object Object]')) throw new Error('headers 需要传递一个 "Object" 类型数据 o(*￣︶￣*)o')
  if (!(dataType === undefined || /^(json|string)$/i.test(dataType))) throw new Error('dataType 目前只接受 "json" 或者 "string" 两种值')
  if (!(success === undefined || typeof success === 'function')) throw new Error('success 需要传递一个 "Function" 类型数据')
  const _default = {
    url: url,
    method: method || 'GET',
    async: async ?? true,
    data: data || '',
    headers: { 'content-type': 'application/x-www-form-urlencoded', ...headers },
    dataType: dataType || 'string',
    success: success || function () {}
  }
  if (typeof _default.data === 'object') _default.data = queryStringify(_default.data)
  if (/^get$/i.test(_default.method) && _default.data) _default.url += '?' + _default.data
  const xhr = new XMLHttpRequest()
  xhr.open(_default.method, _default.url, _default.async)
  xhr.onload = function () {
    const res = _default.dataType === 'string' ? xhr.responseText : JSON.parse(xhr.responseText)
    _default.success(res)
  }
  for (let k in _default.headers) xhr.setRequestHeader(k, _default.headers[k])
  ;/^get$/i.test(_default.method) ? xhr.send() : xhr.send(_default.data)
}
function pAjax(options = {}) {
  return new Promise((resolve, reject) => {
    ajax({
      url: options.url,
      data: options.data,
      async: options.async,
      method: options.method,
      headers: options.headers,
      dataType: options.dataType,
      success (res) {
        resolve(res)
      }
    })
  })
}